package com.tcm.prescribe.service;


import cn.hutool.core.util.ObjectUtil;
import com.base.core.exception.ServiceException;
import com.base.core.utils.R;
import com.base.genid.generator.UidGenerator;
import com.base.core.dozer.DozerConvert;
import com.base.core.pager.PageBean;
import com.base.core.pager.PageContext;
import com.base.core.utils.ListUtils;
import com.tcm.prescribe.api.domain.dto.FrequentDTO;
import com.tcm.prescribe.api.domain.dto.FrequentItemDTO;
import com.tcm.prescribe.api.domain.entity.Frequent;
import com.tcm.prescribe.api.domain.entity.FrequentItem;
import com.tcm.prescribe.api.domain.enums.BusinessCodeEnum;
import com.tcm.prescribe.api.service.FrequentService;
import com.tcm.prescribe.mapper.FrequentItemMapper;
import com.tcm.prescribe.mapper.FrequentMapper;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@DubboService(version = "0.0.1-alpha", retries = 3, timeout = 6000, delay = -1)
public class FrequentServiceImpl implements FrequentService {

    @Autowired
    private FrequentMapper frequentMapper;

    @Autowired
    private FrequentItemMapper frequentItemMapper;

    @DubboReference(version = "0.0.1-beta", group = "cached-uid", timeout = 6000, check = false, retries = 3)
    private UidGenerator uidGenerator;


    /**
     * 分页查询常用方
     *
     * @param userId 医生登录账号id
     * @param start
     * @param pagesize
     * @return
     */
    @Override
    public PageBean<FrequentDTO> listPageByUserId(Long userId, Long start, Long pagesize) throws ServiceException {
        Long total = frequentMapper.countByUserId(userId);
        PageContext.setCurrentPage(start);
        PageContext.setPageSize(pagesize);
        PageContext.setDataCount(total);
        if(total == 0){
            return new PageBean<>(null);
        }

        List<Frequent> frequents = frequentMapper.listPageByUserId(userId, PageContext.getStart(),pagesize);
        List<FrequentDTO> frequentDTOS = null;
        if(ListUtils.isNotEmpty(frequents)){
            frequentDTOS = DozerConvert.copyList(frequents, FrequentDTO.class);
        }
        PageBean<FrequentDTO> frequentDTOPageBean = new PageBean<>(frequentDTOS);
        PageContext.clear();
        return frequentDTOPageBean;
    }

    /**
     * 保存
     *
     * @param frequentDto
     * @return
     */
    @Transactional
    @Override
    public int save(FrequentDTO frequentDto) throws ServiceException {
        if(ObjectUtil.isEmpty(frequentDto)){
            R.throwFail(BusinessCodeEnum.FREQUENT_DATA_NOT_EXISTS);
        }
        Frequent frequent = DozerConvert.copyProperties(frequentDto, Frequent.class);
        frequent.setId(uidGenerator.getUID());
        frequent.setCreateTime(LocalDateTime.now());
        frequent.setUpdateTime(LocalDateTime.now());
        frequent.setDeleted(new Byte("0"));
        if(ListUtils.isNotEmpty(frequentDto.getFrequentItemDtoList())){
            List<FrequentItem> frequentItemList = DozerConvert.copyList(frequentDto.getFrequentItemDtoList(),FrequentItem.class);
            for(FrequentItem frequentItem : frequentItemList){
                frequentItem.setUserId(frequentDto.getUserId());
                frequentItem.setCreateTime(LocalDateTime.now());
                frequentItem.setUpdateTime(LocalDateTime.now());
                frequentItem.setDeleted(new Byte("0"));
                frequentItem.setFrequentId(frequent.getId());
                frequentItem.setId(uidGenerator.getUID());
            }
            frequentItemMapper.insertBatch(frequentItemList);
        }
        return frequentMapper.insert(frequent);
    }

    /**
     * 更新
     *
     * @param frequentDto
     * @return
     */
    @Transactional
    @Override
    public int update(FrequentDTO frequentDto) {
        if(ObjectUtil.isEmpty(frequentDto)){
            R.throwFail(BusinessCodeEnum.FREQUENT_DATA_NOT_EXISTS);
        }
        if(ObjectUtil.isEmpty(frequentDto.getId())){
            R.throwFail(BusinessCodeEnum.ID_NOT_EXISTS);
        }
        Frequent frequent = DozerConvert.copyProperties(frequentDto, Frequent.class);
        frequent.setDeleted(new Byte("0"));
        frequent.setUpdateTime(LocalDateTime.now());
        if(ListUtils.isNotEmpty(frequentDto.getFrequentItemDtoList())){
            //先删除旧数据
            frequentItemMapper.deleteLogicByFrequentId(frequentDto.getId());
            //批量插入新数据
            List<FrequentItem> frequentItemList = DozerConvert.copyList(frequentDto.getFrequentItemDtoList(),FrequentItem.class);
            for(FrequentItem frequentItem : frequentItemList){
                frequentItem.setUserId(frequentDto.getUserId());
                frequentItem.setCreateTime(LocalDateTime.now());
                frequentItem.setUpdateTime(LocalDateTime.now());
                frequentItem.setDeleted(new Byte("0"));
                frequentItem.setFrequentId(frequent.getId());
                frequentItem.setId(uidGenerator.getUID());
            }
            frequentItemMapper.insertBatch(frequentItemList);
        }
        return frequentMapper.update(frequent);
    }

    /**
     * 永久删除
     *
     * @param id
     * @return
     */
    @Override
    public int deleteById(Long id) {
        return frequentMapper.deleteById(id);
    }

    /**
     * 逻辑删除
     *
     * @param id
     * @return
     */
    @Override
    public int deleteLogicById(Long id) {
        return frequentMapper.deleteLogicById(id);
    }

    /**
     * 查询医案信息
     *
     * @param id
     * @return
     */
    @Override
    public FrequentDTO findById(Long id) {
        Frequent frequent = frequentMapper.findById(id);
        FrequentDTO frequentDTO = null;
        if(ObjectUtil.isNotEmpty(frequent)){
            frequentDTO = DozerConvert.copyProperties(frequent, FrequentDTO.class);

            //获取常用方下面的药材
            List<FrequentItem> frequentItems = frequentItemMapper.listItemByFrequentId(id);
            List<FrequentItemDTO> frequentItemVos = null;
            if(ListUtils.isNotEmpty(frequentItems)){
                frequentItemVos = DozerConvert.copyList(frequentItems, FrequentItemDTO.class);
            }
            frequentDTO.setFrequentItemDtoList(frequentItemVos);
        }
        return frequentDTO;
    }
}
